<?php

namespace app\common\server;


class Tree
{
    protected static $config = [
        'icon' => ['│', '├', '└'], //生成树型结构所需修饰符号，可以换成图片
        'parentName' => 'parent_id', //关联的父字段名
        'childName' => 'child', //存储子信息的字段名
        'correlation' => 'id', //关联id名
    ];

    protected static $data = [];

    public static function init($config, $data)
    {
        self::$config = array_merge(self::$config, $config);
        self::$data = is_array($data) ? $data : [];
    }

    protected static function config($name)
    {
        return isset(self::$config[$name]) ? self::$config[$name] : '';
    }

    protected static function getIcon($key)
    {
        return isset(self::$config['icon'][$key]) ? self::$config['icon'][$key] : '';
    }

    protected static function getChild($parentId)
    {
        $result = [
            'nums' => 0,
            'lastId' => 0,
        ];
        foreach (self::$data as $k => $v) {
            if ($v[self::config('parentName')] == $parentId) {
                $result['nums']++;
                $result['lastId'] = $v[self::config('correlation')];
            }
        }
        return $result;
    }

    protected static function getStr($parentId, $level, $name, &$v)
    {
        if (!empty($name) && ($level > 1)) {
            $result = self::getChild($parentId);
            if (($result['nums'] == 1) || ($result['lastId'] == $v[self::config('correlation')])) {
                $v[$name] = self::getIcon(2) . $v[$name];
            } elseif (($result['nums'] > 1) && ($result['lastId'] != $v[self::config('correlation')])) {
                $v[$name] = self::getIcon(1) . $v[$name];
            } else {
                $v[$name] = self::getIcon(0) . $v[$name];
            }
            $v[$name] = str_repeat('&nbsp;&nbsp;' ,($level - 1) * 2) . $v[$name];
        }
    }

    public static function toTreeAppose($parentId, $level = 1, $name = '')
    {
        $arr = [];
        foreach (self::$data as $k => $v) {

            if ($v[self::config('parentName')] == $parentId) {

                self::getStr($parentId, $level, $name, $v);

                $arr[] = $v;

                if (!empty(self::$data[$v[self::config('correlation')]]) && is_array(self::$data[$v[self::config('correlation')]])) $arr = array_merge($arr, self::toTreeAppose($v[self::config('correlation')], $level + 1, $name));

            }
        }
        return $arr;
    }
}